package cn.fl.risk.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cmm.comm.facade.framework.api.ISysDictionaryApiService;
import cmm.comm.facade.framework.dto.SysDictionaryDTO;
import cmm.mid.core.framework.page.Pager;
import cmm.user.facade.system.api.ISysUsrApiService;
import cmm.user.facade.system.condition.SysUsrQueryCondition;
import cmm.user.facade.system.dto.SysUsrDTO;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.risk.condition.RskUsrCstRQueryCondition;
import cn.fl.risk.constant.RiskConstant;
import cn.fl.risk.dto.RskUsrCstRDTO;
import cn.fl.risk.service.IRskUsrCstRApiService;
import cn.fl.risk.service.IRskUsrCstRService;
import cn.fl.risk.transform.RskUsrCstRVOTransform;
import cn.fl.risk.vo.RskUsrCstRVO;

/**
 * @Description: 催收员客户关系表 客户端服务层接口实现
 * 业务层方法名称前缀：
 * 新增：add*
 * 删除：remove*
 * 修改：modify*
 * 批量：batch*
 * 查询对象：select* get*
 * 查询集合：search*
 */
@Service
public class RskUsrCstRServiceImpl implements IRskUsrCstRService {

	/**
     * 日志
     */
    @SuppressWarnings("unused")
    private static final Logger logger = LoggerFactory.getLogger(RskUsrCstRServiceImpl.class);
	
	/**
	 * TODO 自定义 API 暴露服务
	 */
	@Autowired
	private IRskUsrCstRApiService rskUsrCstRApiService;
	/**
     * 数据字典服务
     */
    @Autowired
    private ISysDictionaryApiService sysDictionaryApiService;
    @Autowired
    private ISysUsrApiService sysUsrApiService;

	@Override
	public RskUsrCstRVO selectById(Long id) throws BaseException{
		if(StringUtils.isEmpty(id)) return null;
		RskUsrCstRDTO dto = this.rskUsrCstRApiService.selectRskUsrCstRById(id);
		return RskUsrCstRVOTransform.toVO(dto);
	}

	@Override
    public Long add(RskUsrCstRVO entity) throws BaseException{
        if(null == entity) return null;
        return this.rskUsrCstRApiService.addRskUsrCstR(RskUsrCstRVOTransform.toDTO(entity));
    }

    @Override
    public boolean addR(RskUsrCstRVO entity) throws BaseException{
        if(null == entity) return false;
        return this.rskUsrCstRApiService.batchAddRskUsrCstR(RskUsrCstRVOTransform.toDTO(entity));
    }

	@Override
	public boolean removeByIds(List<Long> ids) throws BaseException{
		if(CollectionUtils.isEmpty(ids)) return false;
		return this.rskUsrCstRApiService.removeRskUsrCstRByIds(ids,CurrentThreadContext.getCurrentUserId());
	}

	@Override
	public boolean modify(RskUsrCstRVO entity) throws BaseException{
		if(null == entity) return false;
		return this.rskUsrCstRApiService.modifyRskUsrCstR(RskUsrCstRVOTransform.toDTO(entity));
	}

	@Override
	public Pager searchListPage(Pager page) throws BaseException{
        RskUsrCstRQueryCondition condition=null;
        if(null == page) {
            page = new Pager();
            page.setCondition(new RskUsrCstRQueryCondition());
        }
		condition=(RskUsrCstRQueryCondition)page.getCondition();
        condition.setSysCd(CurrentThreadContext.getCurrentSysCd());//当前系统代码
        condition.setOrgCd(CurrentThreadContext.getCurrentOrgCd());//当前机构代码
        condition.setUsrId(CurrentThreadContext.getCurrentUserId());//当前用户ID
		page=this.rskUsrCstRApiService.searchRskUsrCstRListPage(page);
		if(CollectionUtils.isNotEmpty(page.getResultList())){
            List<RskUsrCstRVO> voList=RskUsrCstRVOTransform.toVOList((List<RskUsrCstRDTO>)page.getResultList());
            //this.setDictData(voList);
            page.setResultList(voList);
        }
        return page;
	}
	
	@Override
	public List<RskUsrCstRVO> searchList(RskUsrCstRQueryCondition condition) throws BaseException{
		if(null == condition) condition=new RskUsrCstRQueryCondition();
		condition.setSysCd(CurrentThreadContext.getCurrentSysCd());//当前系统代码
		condition.setOrgCd(CurrentThreadContext.getCurrentOrgCd());//当前机构代码
		condition.setUsrId(CurrentThreadContext.getCurrentUserId());//当前用户ID
		List<RskUsrCstRVO> voList=RskUsrCstRVOTransform.toVOList(this.rskUsrCstRApiService.searchRskUsrCstRList(condition));
		this.setDictData(voList);
		return voList;
	}

    /*********************************
     * 查询每个催收员的任务数
     * @param condition
     * @return
     * @throws BaseException
     ********************************/
    public List<RskUsrCstRVO> searchTaskQtyByUsr(RskUsrCstRQueryCondition condition) throws BaseException{
        if(null == condition) condition=new RskUsrCstRQueryCondition();
        condition.setSysCd(CurrentThreadContext.getCurrentSysCd());//当前系统代码
        condition.setOrgCd(CurrentThreadContext.getCurrentOrgCd());//当前机构代码
        condition.setUsrId(CurrentThreadContext.getCurrentUserId());//当前用户ID
        List<RskUsrCstRVO> voList=RskUsrCstRVOTransform.toVOList(this.rskUsrCstRApiService.searchRskUsrCstRList(condition));
        this.setDictData(voList);
        return voList;
    }

    /*******************************
     * 查询分配催收任务客户列表
     * @param page
     * @return
     * @throws BaseException
     *******************************/
    @Override
    public Pager searchCstList(Pager page) throws BaseException {
        SysUsrQueryCondition condition=null;
        if(null == page) {
            page = new Pager();
            page.setCondition(new SysUsrQueryCondition());
        }
        condition=(SysUsrQueryCondition)page.getCondition();
        condition.setSysCd(CurrentThreadContext.getCurrentSysCd());
        //设置评审人员角色
        List<SysDictionaryDTO> sysDictionaryDTOList = this.sysDictionaryApiService.searchGroup(CurrentThreadContext.getCurrentSysCd(),CurrentThreadContext.getCurrentOrgCd(), RiskConstant.CODE_COLLECTOR_ROLE_CD);
        if(CollectionUtils.isNotEmpty(sysDictionaryDTOList)){
            //TODO 多个角色
            /*List<Long> roleIds=new ArrayList<>(sysDictionaryDTOList.size());
            for(SysDictionaryDTO sysDictionaryDTO:sysDictionaryDTOList){
                roleIds.add(Long.valueOf(sysDictionaryDTO.getCode()));
            }*/
            condition.setRoleId(Long.valueOf(sysDictionaryDTOList.get(0).getCode()));
        }
        page=this.sysUsrApiService.searchAuthSysUsrListPage(page);
        if(CollectionUtils.isNotEmpty(page.getResultList())){
            List<SysUsrDTO> dtoList=(List<SysUsrDTO>)page.getResultList();
            List<Long> cstIdList=new ArrayList<>(dtoList.size());
            for(SysUsrDTO sysUsrDTO:dtoList){
                cstIdList.add(sysUsrDTO.getId());
            }
            //查询催收用户的客户数（任务数）
            RskUsrCstRQueryCondition usrCstRQueryCondition=new RskUsrCstRQueryCondition();
            usrCstRQueryCondition.setCstIdList(cstIdList);
            List<RskUsrCstRDTO> rList=this.rskUsrCstRApiService.searchTaskQtyByUsr(usrCstRQueryCondition);
            Map<Long,Long> qtyMap=null;
            if(CollectionUtils.isNotEmpty(rList)){
                qtyMap=new HashMap<>(rList.size());
                for(RskUsrCstRDTO cstRDTO:rList){
                    qtyMap.put(cstRDTO.getUsrId(),cstRDTO.getCstQty());
                }
            }

            //拼装结果集
            List<RskUsrCstRVO> voList=new ArrayList(dtoList.size());
            RskUsrCstRVO vo=null;
            for(SysUsrDTO sysUsrDTO:dtoList){
                vo=new RskUsrCstRVO();
                vo.setUsrId(sysUsrDTO.getId());
                vo.setUsrNm(sysUsrDTO.getRefRlNm());
                if(qtyMap!=null&&qtyMap.containsKey(sysUsrDTO.getId())){
                    vo.setTaskQty(qtyMap.get(sysUsrDTO.getId()));
                }else{
                    vo.setTaskQty(0L);
                }
                voList.add(vo);
            }
            page.setResultList(voList);
        }
        return page;
    }

    /**
     * 添加数据字典名称
     * @param voList
     */
	public void setDictData(List<RskUsrCstRVO> voList){
		if(CollectionUtils.isEmpty(voList)) return;
		/*Map<String, String> _CdMap = this.sysDictionaryApiService.searchGroupToMap(sysCd, orgCd, RskUsrCstRConstant.CODE_CD);
		for(RskUsrCstRVO vo:voList){
			if (_CdMap != null && _CdMap.containsKey(vo.getCd())) {
            	vo.setCdNm(_CdMap.get(vo.getCd()));
        	}	
		}*/
	}
	    
}
